package ltd.followkba.page;

import android.view.View;

import androidx.recyclerview.widget.GridLayoutManager;

import com.kcbsdk.EventHandler;
import com.kcbsdk.MyWorks.APhotoInfo;

import java.util.ArrayList;
import java.util.List;

import ltd.advskin.MRAM;
import ltd.advskin.MSKIN;
import ltd.advskin.base.BaseList;
import ltd.advskin.base.BasePage;

import ltd.advskin.base.KcListHolder;
import ltd.advskin.base.KcListListener;
import ltd.advskin.base.KcTypeListener;
import ltd.advskin.task.TaskFree;
import ltd.advskin.utils.SysUtils;
import ltd.advskin.view.KcHeaderView;
import ltd.advskin.view.KcListView;
import ltd.followkba.MAPP;
import ltd.followkba.R;
import ltd.followkba.task.App33;
import ltd.followkba.task.BAppUser;
import ltd.followkba.task.BAppWorks;
import ltd.followkba.task.EditUtils;
import main.MAPI;

import static ltd.advskin.MSKIN.MSTRING;
import static ltd.advskin.MSKIN.MTOAST;
import static ltd.advskin.view.KcListView.LIST_SPAN_SIZE;
import static main.MAPI.mMyWorks;

public class PhotoWorksPage extends BaseList {
    private BAppUser mBAppUser;
    private List<APhotoInfo> mAPhotoInfo;
    private String gsResult;
    private boolean isChange;
    private boolean isMyPhoto;

    // 所有的页面都接受同样的方式打开LOG
    public static boolean logEnable;
    public void MLOG(String text) {
        if (logEnable) {
            MSTRING(MAPI.GET_LOG_NAME(this) + text);
        }
    }

    @Override
    public void onInitView() {                       // 使用者需要继承，初始化页面控件等显示
        setLayout(R.layout.page_simple_list);
        if (mBaseInput != null) {                   // 可能仅仅需要刷新，未必是重新开始的
            mBAppUser = mBaseInput.getInput(0);
            mBaseInput = null;                  // 输入参数的使命已经完成，记得及时销毁之
        }
        mKcHeaderView = (KcHeaderView) findViewById(R.id.khvSimpleList);
        isMyPhoto = (mBAppUser == null || mBAppUser.UserIdS.equals(MAPP.mBDbsAccount.UserIdS)) ? true : false;
        String text = isMyPhoto ? "管理我的头像" : "用户头像图片列表";
        mKcHeaderView.setTitle(text, new KcTypeListener() {
            @Override
            public void onMessage(int type) {
                switch (type) {
                    case KcHeaderView.TYPE_CLICK_LEFT:
                        onFinish();
                        break;
                }
            }
        });
        initPageListView( 1 );
    }
    @Override
    public void onInitData(){                                                                       // onInitView结束，开始加载数据
            getPhotoList();

        mMyWorks.setUiEventCallBack(new EventHandler() {
            @Override
            public void onComplete(int methodType, boolean isFail, String message) {
                if (methodType > 0) {
                }else {
                    if (mMyWorks.isEventDataRefresh()){
                        showInfo();
                    }
                }
            }
        });
        showInfo();
    }
    @Override
    public void onPageUpdate(BasePage basePage) {    // 更新显示页面数据，用于刷新显示 basePage返回上面的页面，可以使用getPageResult()获得返回的内容
        onInitData();
    }
    @Override
    public void onFinish() {       // 使用者选择性继承，用户按了后退键，不继承就直接关闭了
        if (isChange){
            setPageResult(this);
        }
        setClose();
    }
    private void showInfo() {
        if (mAPhotoInfo != null){
            setListView(gTabSelect, (List) mAPhotoInfo);
        }
    }
    private void getPhotoList() {
        mAPhotoInfo = new ArrayList<>();
        BAppWorks bPhotoWorks = null;
//        App33 app33 = MAPP.mAccount33;
        if ((MAPP.mBDbsAccount.WorksType == 33 || MAPP.mBDbsAccount.WorksType == 49)) {
            bPhotoWorks = App33.getPhotoAlbum(mBAppUser.UserIdS);
        }
        SysUtils sysUtils = new SysUtils();
        int length = bPhotoWorks != null ? bPhotoWorks.Photos.length : 0;
        for (int index = 0; index < length; index++){
            APhotoInfo aPhotoInfo = bPhotoWorks.Photos[index];
            aPhotoInfo.FileName = String.format("%sphoto/P%02x_%s.jpg", MRAM.gsCachePath, MAPP.mBDbsAccount.WorksType, sysUtils.getStringMd5(aPhotoInfo.FileUrl));
            String result = sysUtils.getUrlFile(aPhotoInfo.FileUrl, aPhotoInfo.FileName);
            if ("error,4".equals(result)){
                aPhotoInfo.FileUrl = aPhotoInfo.FileUrl.replace(".jpg", "_640_640.jpg");
                result = sysUtils.getUrlFile(aPhotoInfo.FileUrl, aPhotoInfo.FileName);
            }
            MLOG(String.format("APhotoInfo A %s %s %s %s", index, result, MAPI.GET_FILE_LENGTH(aPhotoInfo.FileName), aPhotoInfo.FileUrl));
            mAPhotoInfo.add(aPhotoInfo);
        }
    }
    private void setHeadOrDelete(APhotoInfo aPhotoInfo, final boolean isDelete){
        if (isMyPhoto) {
            gsResult = null;
            new TaskFree(aPhotoInfo, new TaskFree.Listener() {
                @Override
                public void onMessage(boolean isThread, Object object) {
                    APhotoInfo aPhotoInfo = (APhotoInfo) object;
                    if (isThread) {
//                        App33 app33 = MAPP.mAccount33;
                        if ((MAPP.mBDbsAccount.WorksType == 33 || MAPP.mBDbsAccount.WorksType == 49)) {
                            if (isDelete) {
                                gsResult = App33.deletePhotoAlbum(aPhotoInfo.PhotoID);
                            }else {
                                gsResult = App33.setHeadPhoto(aPhotoInfo.PhotoID);
                            }
                        }

//                        if (isDelete) {
//                            App33 app33 = MAPP.mAccount33;
//                            if (MAPP.mBDbsAccount.WorksType == 33) {
//                                gsResult = app33.deletePhotoAlbum(aPhotoInfo.PhotoID);
//                                MLOG(String.format("String PhotoID del %s %s", aPhotoInfo.PhotoID, gsResult));
//                            }
//                            getPhotoList();
//                        } else {
//                            if (MAPP.mBDbsAccount.WorksType == 33) {
//                                gsResult = app33.setHeadPhoto(aPhotoInfo.PhotoID);
//                                MLOG(String.format("String PhotoID %s %s", aPhotoInfo.PhotoID, gsResult));
//                            }
//                        }
                        return;
                    }
                    if ("ok".equals(gsResult)) {
                        isChange = true;
                        if (isDelete) {
                            MTOAST("删除图片成功");
                        } else {
                            MTOAST("已设为当前头像");
//                        MAPI.DELETE_FILE(MAPP.mBDbsAccount.HeadFile);
                            EditUtils editUtils = new EditUtils();
                            editUtils.getAndSaveBDbsAccountInfo(null);
                        }
                        showInfo();
                    } else {
                        if (isDelete) {
                            MTOAST(String.format("删除图片出错：%s", gsResult));
                        } else {
                            MTOAST(String.format("设为当前头像出错：%s", gsResult));
                        }
                    }
                }
            });
        }
    }
    private static final int[] item_photo_list = new int[]{
            R.layout.item_photo_list, 2,
            R.id.kbiPhotoList, R.id.kbtDeletePhoto,
    };
    ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    // KcListView的全部处理，放在页面的最后位置统一处理 ///////////////////////////////////////////////////////////////////
    ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    private void initListView(int tab, KcListView kcListView) {
        mKcListView[tab] = kcListView;
        GridLayoutManager layoutManager = new GridLayoutManager(MRAM.mActivity, 12);
        mKcListView[tab].initView(null, item_photo_list, layoutManager, new KcListListener() {
            @Override
            public int onMessage(int type, int tab, Object object) {
                switch (type) {
                    case LIST_SPAN_SIZE:              // 每行个数不规则的调整(需要这个layoutManager)  spanCount（数值随便定）除以return（数值随便定)后面的数字，就是等于你一行需要的个数
                        return 4;
                }
                return 0;
            }
            @Override
            public int onBindItemHolder(boolean skipImage, int tab, int position, final KcListHolder holder) {
                APhotoInfo aPhotoInfo = (APhotoInfo) getListView(tab, position);
                MSKIN.setBitmap(aPhotoInfo.FileName, holder.mView[0]);
                holder.mView[0].setTag(aPhotoInfo);
                holder.mView[0].setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        setHeadOrDelete((APhotoInfo) v.getTag(), false);
                    }
                });
                holder.mItemView.setTag(aPhotoInfo);
                holder.mItemView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        setHeadOrDelete((APhotoInfo) v.getTag(), false);
                    }
                });
                holder.mView[1].setVisibility(isMyPhoto ? View.VISIBLE : View.GONE);
                holder.mView[1].setTag(aPhotoInfo);
                holder.mView[1].setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        setHeadOrDelete((APhotoInfo) v.getTag(), true);
                    }
                });
                return 0;
            }
        });
        // (d)列表最后更新日期时间 (n)下次更新日期时间 (c)当前数量 (q)列表最大的数量
        mKcListView[tab].setStatus(false, false, "", "", "");
        mKcListView[tab].setTabNumber(tab);
    }

    private void initPageListView(int tabQty) {
        mKcListView = new KcListView[tabQty];
        if (tabQty == 1) {
            mKcListView[0] = (KcListView) findViewById(R.id.klvSimpleList);
            mKcListView[0].setVisibility(View.VISIBLE);
            initListView(0, mKcListView[0]);
            return;
        }
    }

}

